// ==UserScript==
// @name         沿着岸边，切开雨线，沉默的漂流瓶浮于水面
// @namespace    https://www.thiswebsitewillselfdestruct.com/
// @version      0.5
// @description  随机查看一条来自世界各地的留言！数据来自一个有趣的网站：https://www.thiswebsitewillselfdestruct.com/
// @author       一语子
// @include      *
// @icon         https://gitee.com/yiyuzi/image/raw/master/img/yiyuzi/piaoliuping.png
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js
// @connect      thiswebsitewillselfdestruct.com
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// @grant        GM_unregisterMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

'use strict';
// console.log("漂流瓶 start");

var menu_ALL = [
    ['menu_ball_pos_top', '球初始位置（距上）', '球位置（距上）', '20'],
    ['menu_ball_pos_left', '球初始位置（距左）', '球位置（距左）', '80'],
    ['menu_ball_height', '球直径', '球直径', '40'],
    ['menu_letter_color_from', '正文颜色（左）', '正文颜色（左）', '#fff'],
    ['menu_letter_color_to', '正文颜色（右）', '正文颜色（右）', '#87CEFA'],
    ['menu_letter_pos_top', '正文位置（距上）', '正文位置（距上）', '0'],
    ['menu_letter_pos_left', '正文位置（距左）', '正文位置（距左）', '0'],
    ['menu_letter_width', '正文宽度', '正文宽度', '600']
], menu_ID = [];

ballInit();

// 设置
function menu_setting(title, line, menu) {
    let _br = '', _html = `<style>
        #all_light { /*整个弹窗的页面*/
            opacity: 0.8; /*透明度*/
            width: 100%; /*宽度*/
            height: 100%; /*高度，不能百分百*/
            background: #000; /*背景色*/
            position: fixed;
            top: 0;
            left: 0; /*定位*/
            display: block; /*隐藏*/
            z-index: 200; /*覆盖*/
        }
        #contes { /* 弹框的页面*/
            z-index: 201;
            position: fixed;
            top: 10%;
            bottom: 10%;
            left: 50%;
            -webkit-transform: translate(-50%, 0%);
            -moz-transform: translate(-50%, 0%);
            -ms-transform: translate(-50%, 0%);
            -o-transform: translate(-50%, 0%);
            transform: translate(-50%, 0%);
            width: auto;
            min-width: 400px;
            max-width: 800px;
            height: auto;
            min-height: 150px;
            color: #535353;
            background-color: #fff;
            border-radius: 3px;
            overflow-x:hidden;
            overflow-y:auto;
        }
        .ballInput{
            margin: 3px;
            outline-style: none ;
            box-shadow: inset 0 0px 0px #000000,0 0 0px #000000;
            padding: 2px;
        }
        .ballInput:focus{
            border-color: #66afe9;
            outline: 0;
            -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);
            box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)
        }
        #closeBtn, #defaultBtn, #submitBtn{
            margin: 10px;
            padding: 5px;
            border-radius: 5px;
            background: #4B98F0;
            color: #fff;
            cursor: pointer;
        }</style>
        <div id="contes">
        <div><div style="padding-left: 10px; padding-top: 5px"><h2>${title}</h2></div>
        <hr> <form id="ballSettingForm" style="margin-left: 15%;">
        `
    if (line) _br = '<br>'
    for (let i=0; i<menu.length; i++) {
        if (GM_getValue(menu[i][0])) {
            _html += `<label style =" width: 40%; display: inline-block;">${menu[i][1]}</label><input id="${menu[i][0]}" class="ballInput" name="${menu[i][0]}" type="input" value="${GM_getValue(menu[i][0])}">${_br}`
        } else {
            _html += `<label style =" width: 40%; display: inline-block;">${menu[i][1]}</label><input id="${menu[i][0]}" class="ballInput" name="${menu[i][0]}" type="input" value="${menu[i][3]}">${_br}`
        }
    }
    _html += `<input id="closeBtn" type="button" value="关闭"><input id="defaultBtn" type="button" value="恢复默认值"><input id="submitBtn" type="button" value="应用"> </form> </div></div><div id="all_light"></div>${_br}`
    document.body.insertAdjacentHTML('beforeend', _html); // 插入网页末尾
    setTimeout(function() { // 延迟 100 毫秒，避免太快
        // 关闭按钮 点击事件
        $('#closeBtn').bind('click', closeSetting);
        // 点击周围空白处 = 点击关闭按钮
        $("#all_light").bind('click', closeSetting);
        $("#defaultBtn").bind('click', function(){
            for (let i=0;i<menu.length;i++){
                $("#"+menu[i][0]).val(menu[i][3]);
            };
        });
        $('#submitBtn').bind('click', function(){
            for (let i=0; i<menu.length; i++) {
                GM_setValue(menu[i][0], $("#"+menu[i][0]).val());
            }
            setBallStyle();
        });
    }, 100)
}

function closeSetting(){
    $("#all_light").remove();
    $('#contes').remove();
}

function ballInit(){
    for (let i=0;i<menu_ALL.length;i++){ // 如果读取到的值为 null 就写入默认值
        if (GM_getValue(menu_ALL[i][0]) == null){GM_setValue(menu_ALL[i][0], menu_ALL[i][3])};
    }
    GM_registerMenuCommand("设置", function(){menu_setting("设置", true, menu_ALL)});

    $("body").append("<img id=\"ballId\" src=\"https://gitee.com/yiyuzi/image/raw/master/img/yiyuzi/piaoliuping.png\"  alt=\"漂流瓶\" />");
    setBallStyle();
    suspensionBall('ballId');
}

function setBallStyle(){
    $(".ballStyle").remove();
    $("html").append("<style class=\"ballStyle\">" +
      "#ballId {" +
      "width: " + GM_getValue("menu_ball_height") + "px;" +
      "height: " + GM_getValue("menu_ball_height") + "px;" +
      "border-radius: 50%;" +
      "transform: translate3d(-50%, -50%, 0);" +
      "top: " + GM_getValue("menu_ball_pos_top") + "%;" +
      "left: " + GM_getValue("menu_ball_pos_left") + "%;" +
      "z-index: 999;" +
      "}" +
      "#thiswebsitewillselfdestruct {" +
      "background: -webkit-gradient(linear,0 0,100% 100%,from(" + GM_getValue("menu_letter_color_from") + "), to(" + GM_getValue("menu_letter_color_to") + "));" +
      "color: black;" +
      "width: " + GM_getValue("menu_letter_width") + "px;" +
      "height: auto;" +
      "max-height: "+ (92 - GM_getValue("menu_letter_pos_top")) +"%;" +
      "padding: 10px;" +
      "border-radius: 15px;" +
      "z-index: 100;" +
      "position:fixed;" +
      "overflow-x:hidden;" +
      "overflow-y:auto;" +
      "white-space: pre-wrap; word-wrap: break-word;" +
      "top: " + GM_getValue("menu_letter_pos_top") + "%;" +
      "left: " + GM_getValue("menu_letter_pos_left") + "%;" +
      "text-align: left;" +
      "}"+
      "#thiswebsitewillselfdestruct::-webkit-scrollbar {/*display:none;*/background: "+GM_getValue("menu_letter_color_to")+";border-radius: 15px;}"+
      "#thiswebsitewillselfdestruct::-webkit-scrollbar-thumb {background: "+GM_getValue("menu_letter_color_from")+";border-radius: 15px;}"+
      "</style>");
};

function suspensionBall(dragId) {
  var startEvt, moveEvt, endEvt
  // 判断是否支持触摸事件
  if ('ontouchstart' in window) {
    startEvt = 'touchstart'
    moveEvt = 'touchmove'
    endEvt = 'touchend'
  } else {
    startEvt = 'mousedown'
    moveEvt = 'mousemove'
    endEvt = 'mouseup'
  }
  // 获取元素
  var drag = document.getElementById(dragId)
  drag.style.position = 'fixed'
  drag.style.cursor = 'pointer'
  // 标记是拖曳还是点击
  var isClick = true
  // 标记正文是否展开
  var isOpen = false
  // 标记球的位置
  var disX, disY, left, top, starX, starY

  drag.addEventListener(startEvt, function (e) {
    // 阻止页面的滚动，缩放
    e.preventDefault()
    // 兼容IE浏览器
    e = e || window.event
    isClick = true
    // 手指按下时的坐标
    starX = e.touches ? e.touches[0].clientX : e.clientX
    starY = e.touches ? e.touches[0].clientY : e.clientY
    // 手指相对于拖动元素左上角的位置
    disX = starX - drag.offsetLeft
    disY = starY - drag.offsetTop
    // 按下之后才监听后续事件
    document.addEventListener(moveEvt, moveFun)
    document.addEventListener(endEvt, endFun)
  })

  function moveFun(e) {
    // 兼容IE浏览器
    e = e || window.event
    isClick = false
    left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
    top = (e.touches ? e.touches[0].clientY : e.clientY) - disY
    // 限制拖拽的X范围，不能拖出屏幕
    if (left < 0) {
      left = 0
    } else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
      left = document.documentElement.clientWidth - drag.offsetWidth
    }
    // 限制拖拽的Y范围，不能拖出屏幕
    if (top < 0) {
      top = 0
    } else if (top > document.documentElement.clientHeight - drag.offsetHeight) {
      top = document.documentElement.clientHeight - drag.offsetHeight
    }
    drag.style.left = left + 'px'
    drag.style.top = top + 'px'
  }

  function endFun(e) {
    document.removeEventListener(moveEvt, moveFun)
    document.removeEventListener(endEvt, endFun)
    if (isClick) { // 点击
      if (isOpen){
          $("#thiswebsitewillselfdestruct").remove();
          isOpen = false;
      }else {
          var elem = document.createElement("pre");
          elem.id = "thiswebsitewillselfdestruct";
          GM_xmlhttpRequest({
              url:"https://www.thiswebsitewillselfdestruct.com/api/get_letter",
              method :"GET",
              onload:function(xhr){
                  var json = JSON.parse(xhr.responseText);
                  elem.innerHTML = json.body;
              }
          });
          $("body").append(elem);
          isOpen = true;
      }
    }
  }
}